#include "ProjObject.h"

void ProjObject::Release() {
	mesh.Release();
	meshInst.Release();
}

bool ProjObject::Initialize(LPDIRECT3DDEVICE9 pDevice) {
	deleteNextUpdate = false;
	damage = 1.0f;
	distToCam = 0.0f;
	yVelocity = 0.0f;
	initialPosition = D3DXVECTOR3(0,0,0);
	alignment = "Neutral";
	if(modelFile.empty())
		modelFile = " ";
	name = "Unnamed";
	type = "Bullet";
	sourceUnit = NULL;

	InitializePhysicsInfo();

	if(!InitializeMesh(pDevice))
		return false;

	return true;
}

bool ProjObject::InitializeMesh(LPDIRECT3DDEVICE9 pDevice) {
	if(modelFile != " ") {
		//PRINT("Reading from model file: ");
		//PRINT(modelFile.c_str());	NEXT_LINE;
		if(!mesh.Load(pDevice, modelFile)) {
			SHOWERROR("mesh.Load() - Failed", __FILE__, __LINE__);
			return false;
		}
		meshInst.setMesh(&mesh);
	} else {
		PRINT("Model file name not specified, current entry: ");
		PRINT(modelFile.c_str());	NEXT_LINE;
		return false;
	}

	return true;
}

void ProjObject::InitializePhysicsInfo() {
	physicsInfo.destination = D3DXVECTOR3(0,0,0);
	physicsInfo.dirLook = D3DXVECTOR3(0,0,0);
	physicsInfo.velocity = D3DXVECTOR3(0,0,0);
	physicsInfo.turningSpeed = 0.2f;
	physicsInfo.maxTurningSpeed = 5.0f;
	physicsInfo.maxVelocity = 0.3f;
}

void ProjObject::Update(float elapsedTime) {
	physicsInfo.velocity = *(D3DXVec3Normalize(&physicsInfo.velocity, &physicsInfo.dirLook)) * (physicsInfo.maxVelocity * elapsedTime);
	
	if(type == "Bomb") {
		physicsInfo.maxVelocity -= physicsInfo.maxVelocity * (g_AtmosphericResistance * elapsedTime);
		yVelocity -= g_Gravity;
		physicsInfo.velocity.y = yVelocity;

		if(physicsInfo.velocity.y >= g_FreeFallTerminalVelocity) {
			physicsInfo.velocity.y = g_FreeFallTerminalVelocity;
		}
	}

	UpdateMovement(elapsedTime);
}

void ProjObject::UpdateMovement(float elapsedTime) {
	meshInst.translateRel(physicsInfo.velocity.x, physicsInfo.velocity.y * elapsedTime, 
		physicsInfo.velocity.z);
}

void ProjObject::Render(LPDIRECT3DDEVICE9 pDevice) {
	meshInst.Render(pDevice);
}
